package com.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.util.Set;

public class Server {
    public static void main(String[] args) {
        new Server();
    }
    private String ip;
    private int port;
    private ByteBuffer readBuffer;
    private ByteBuffer writeBuffer;
    private Selector selector;

    public Server() {
        this("localhost", 8111, 512);
    }

    public Server(String ip, int port, int bufferLength) {
        this.ip = ip;
        this.port = port;
        this.readBuffer = ByteBuffer.allocate(bufferLength);
        this.writeBuffer = ByteBuffer.allocate(bufferLength);
        initServer();
    }
//SelectKey 四大事件

    /**
     *
     */
    //初始化
    private void initServer() {
        try {
            //打开网络通道
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置通道是非阻塞
            serverSocketChannel.configureBlocking(false);
            //设置服务端ip和端口
            ServerSocket serverSocket = serverSocketChannel.socket();
            serverSocket.bind(new InetSocketAddress(ip, port));//绑定ip和端口
            //实例化先择器
            selector = Selector.open();
            //将指定的通道注册到选择其中并指定监听事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务端已经启动=" + ip + ":" + port);
            handlerListen();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //事件监听
    private void handlerListen() {
        try {
            while (true) {
                selector.select();//获取事件，如果没有就阻塞
                Set<SelectionKey> keys = selector.selectedKeys();
                for (SelectionKey key : keys) {
                    handler(key);
                }
                keys.clear();//清空
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private Scanner scanner = new Scanner(System.in);

    //处理事件
    public void handler(SelectionKey key) {
        try {
            if (key.isAcceptable()) {//有连接了
                ServerSocketChannel server = (ServerSocketChannel) key.channel();
                SocketChannel clientChannel = server.accept();
                clientChannel.configureBlocking(false);
                clientChannel.register(selector, SelectionKey.OP_READ);//注册为读取
            } else if (key.isReadable()) {
                //可以读取
                SocketChannel clientChannel = (SocketChannel) key.channel();
                readBuffer.clear();
                int len = clientChannel.read(readBuffer);
                readBuffer.flip();
                System.out.println("客户端说：" + new String(readBuffer.array(), 0, len));
                System.out.println("请输入要回复的内容：");
                String reply=scanner.nextLine();
                if (len > 0) {
                    writeBuffer.clear();
                    writeBuffer.put(reply.getBytes());
                    writeBuffer.flip();
                    clientChannel.write(writeBuffer);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
